import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
    state:{
        shopcartList:[],
        num:0
    },
    mutations:{
       getShopcartList_Sync(state,payload){
         console.log('------2、store中的mutations的getShopcartList_Sync--------------');
         console.log('payload',payload);
         state.shopcartList=payload
       },
       increment_Sync(state){
         state.num++
       }
    },
    //完成异步操作
    actions:{
       async getShopcartList_Async(context){
          console.log('------1、store中的actions的getShopcartListAsync--------------');
          let result=await Vue.prototype.$api.shopcart.getShopcartData()
          context.commit('getShopcartList_Sync',result.data)
       },
       async checkedProduct_Async(context,payload){
         console.log('------1、store中的actions的checkedProduct_Async--------------',payload);
         let result=await Vue.prototype.$api.shopcart.checkProducts(payload)
         if(result.code){
            //在actions中方法调用actions中的方法
            context.dispatch('getShopcartList_Async')
         }
       },
       async changeNum_Async(context,payload){
         console.log('------1、store中的actions的changeNum_Async--------------',payload);
         let result=await Vue.prototype.$api.shopcart.changeNum(payload)
         if(result.code){
            context.dispatch('getShopcartList_Async')
         }
       }
       

    },
    getters:{
      totalPrice:state=>state.shopcartList.filter(item=>item.checked).reduce((prev,cur)=>prev+cur.price*cur.num,0)
    }
})
//导出store
export default store